package com.lagou.edu.filter;

import com.lagou.edu.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 定义全局过滤器，会对所有路由生效
 */
@Slf4j
@Component  // 让容器扫描到，等同于注册了
@RefreshScope
public class IpFlushFilter implements GlobalFilter, Ordered {

    @Value("${firewall.ip.intervalMinute}")
    private Integer intervalMinute;
    @Value("${firewall.ip.maxHit}")
    private Integer maxHit;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 过滤器核心方法
     *
     * @param exchange 封装了request和response对象的上下文
     * @param chain    网关过滤器链（包含全局过滤器和单路由过滤器）
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("IpFlushFilter ------ {} {}", intervalMinute, maxHit);
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String ip = request.getRemoteAddress().getHostName();
        if (isIpLimited(ip)) {
            return handleReject(response);
        }
        // 合法请求，放行，执行后续的过滤器
        return chain.filter(exchange);
    }

    private boolean isIpLimited(String ip) {
        recordNewIpRequest(ip);
        Long retainIpHits = countEffectiveIntervalIpHit(ip);
        return isOverMaxLimit(retainIpHits.intValue());
    }

    private boolean isOverMaxLimit(Integer nowCount) {
        return nowCount > maxHit;
    }

    private Long countEffectiveIntervalIpHit(String ip) {
        long nowTime = System.currentTimeMillis() / 1000;
        String ipHitStartTimeCacheKey = getIpHitStartTimeCacheKey(ip);
        // 删除统计周期外的计数
        redisUtil.zRemRangeByScore(ipHitStartTimeCacheKey, 0, nowTime - intervalMinute * 60);
        return redisUtil.zCard(ipHitStartTimeCacheKey);
    }

    // 每次访问必须记录
    private void recordNewIpRequest(String ip) {
        long nowTime = System.currentTimeMillis() / 1000;
        String ipHitStartTimeCacheKey = getIpHitStartTimeCacheKey(ip);
        redisUtil.zAdd(ipHitStartTimeCacheKey, ip + "-" + System.nanoTime() + "-" + Math.random(), nowTime);
        redisUtil.expire(ipHitStartTimeCacheKey, intervalMinute * 60);
    }

    private String getIpHitStartTimeCacheKey(String ip) {
        return "secure.ip.limit." + ip + ".starttime";
    }

    private Mono<Void> handleReject(ServerHttpResponse response) {
        response.setStatusCode(HttpStatus.FORBIDDEN); // 状态码
        String data = "Request be forbidden!";
        DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
        return response.writeWith(Mono.just(wrap));
    }

    /**
     * 返回值表示当前过滤器的顺序(优先级)，数值越小，优先级越高
     *
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
